package me.seu.demo.service.wechat;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.seu.demo.service.wechat.message.Message;
import me.seu.demo.service.wechat.model.SendResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;


/**
 * 企业微信机器人发送消息
 *
 * @author liangfeihu
 * @since 2021/10/19 16:56
 */
@Slf4j
public class WxChatRobotClient {

    private static String robotPath = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s";

    private static final RestTemplate restTemplate = new RestTemplate();

    public static SendResult send(String webHookKey, Message message) {
        SendResult sendResult = new SendResult();
        if (StringUtils.isBlank(webHookKey)) {
            log.info("WxChatRobotClient send webHookKey is empty");
            sendResult.setErrorMsg("webHookKey must not be empty");
            return sendResult;
        }

        String requestUrl = String.format(robotPath, webHookKey);
        try {
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> httpEntity = new HttpEntity<String>(message.toJsonString(), headers);

            ResponseEntity<String> responseEntity = restTemplate.postForEntity(requestUrl, httpEntity, String.class);
            if (responseEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
                String body = responseEntity.getBody();
                JSONObject obj = JSONObject.parseObject(body);

                Integer errcode = obj.getInteger("errcode");
                sendResult.setErrorCode(errcode);
                sendResult.setErrorMsg(obj.getString("errmsg"));
                sendResult.setIsSuccess(errcode.equals(0));
            } else {
                sendResult.setErrorCode(responseEntity.getStatusCodeValue());
                sendResult.setErrorMsg("invoke post request error");
            }
        } catch (Exception e) {
            log.error("WxChatRobotClient send IOException {}", requestUrl, e);
            sendResult.setErrorCode(HttpStatus.BAD_REQUEST.value());
            sendResult.setErrorMsg(e.getMessage());
        }
        return sendResult;
    }

}


